package com.egao.common.module.system.transfer;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.egao.common.core.web.JsonResult;
import com.egao.common.module.company.constants.CheckRecordConstants;
import com.egao.common.module.company.entity.Company;
import com.egao.common.module.company.entity.Position;
import com.egao.common.module.company.entity.Recruit;
import com.egao.common.module.company.service.CompanyService;
import com.egao.common.module.company.service.PositionService;
import com.egao.common.module.company.service.RecruitService;
import com.egao.common.module.push.entity.PositionMatching;
import com.egao.common.module.push.service.PositionMatchingService;
import com.egao.common.module.system.entity.User;
import com.egao.common.module.system.entity.UserRole;
import com.egao.common.module.system.service.UserRoleService;
import com.egao.common.module.system.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 单位数据导入
 * @author: dl
 */
@RestController
@Slf4j
public class RecruitDataController<mian> {

    @Value("${old.datasource.jyurl}")
    private String url;

    @Value("${old.datasource.username}")
    private String userName;

    @Value("${old.datasource.password}")
    private String password;

    @Value("${minio.old-data-head}")
    private String contentUrl;

    @Autowired
    private CompanyService companyService;

    @Autowired
    private RecruitService recruitService;

    @Autowired
    private PositionService positionService;

    @Autowired
    private PositionMatchingService positionMatchingService;

    @Transactional(rollbackFor = Exception.class)
    public JsonResult transfer() {
        Connection conn = null;
        Statement st = null;
        ResultSet rs = null;
        long beginTime = System.currentTimeMillis();
        List<Position> positionList = getPositionList();
        List<Company> companyList = getCompanyList();
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection(url, userName, password);
            st = conn.createStatement();
            String sql = "SELECT id,companyid,title,worktype,validtime,jobname,number,workplace,major,education,salarytype,salary," +
                    "welfare,customwelfare,comment,ismail,checkuserid,checkstatecontent,checkstate,checktime," +
                    "recruittype,create_date,del_flag,create_by,update_by,update_date,remarks,type,hits,invalid," +
                    "email,tel,recruiturl,linkman,auditor,ip,companyname,position_ids,position_names," +
                    "field_id,hold_date,hold_date_int,hold_time,push_list,push_flag FROM recruit";
            st = conn.createStatement();
            rs = st.executeQuery(sql);
            log.info("总数：{}", rs.getRow());
            int i = 0;
            int j = 0;
            while (rs.next()) {
                String oldId = rs.getString("id");
                String title = rs.getString("title");
                String worktype = rs.getString("worktype");

                String jobname = rs.getString("jobname");
                String number = rs.getString("number");
                String area = rs.getString("workplace");
                String majors = rs.getString("major");
                String salary = rs.getString("salary");
                String comment = rs.getString("comment");
                String education = rs.getString("education");
                Integer checkstate = rs.getInt("checkstate");
                String checkstatecontent = rs.getString("checkstatecontent");
                Integer recruittype = rs.getInt("recruittype");
                Integer type = rs.getInt("type");
                String email = rs.getString("email");
                String tel = rs.getString("tel");
                String recruiturl = rs.getString("recruiturl");
                String linkman = rs.getString("linkman");
                String position_ids = rs.getString("position_ids");
                String position_names = rs.getString("position_names");
                String push_list = rs.getString("push_list");
                String companyid = rs.getString("companyid");
                String push_flag = rs.getString("push_flag");
                Integer hits = rs.getInt("hits");
                Integer invalid = rs.getInt("invalid");
                String del_flag = rs.getString("del_flag");
                Date createDate = new Date(rs.getTimestamp("create_date").getTime());
                Recruit recruit = new Recruit();
                if (rs.getTimestamp("update_date") != null) {
                    Date updateDate = new Date(rs.getTimestamp("update_date").getTime());
                    recruit.setUpdateTime(updateDate);
                }
                if (rs.getDate("validtime") != null) {
                    Date validTime = new Date(rs.getDate("validtime").getTime());
                    recruit.setValidTime(validTime);
                }
                recruit.setHits(hits);
                recruit.setInvalid(invalid);
                recruit.setCreateTime(createDate);
                recruit.setOldId(oldId);
                recruit.setTitle(title);
                // 学校发布
                if (type == 1) {
                    recruit.setAddType("2");
                // 单位发布
                } else if (type == 2) {
                    recruit.setAddType("1");
                // 异常
                } else {
                    recruit.setAddType("3");
                }

                if (salary != null && salary.contains("~") && !salary.contains("面议")) {
                    recruit.setSalaryType("0");
                    // 小写转换
                    salary = salary.toLowerCase()
                            .replaceAll("\\.", "")
                            .replaceAll("\\+", "")
                            .replaceAll("&middot;", "")
                            .replaceAll(" ", "");
                    log.info(salary);
                    // 数据转换
                    if (salary.contains("k")) {
                        salary = salary.replaceAll("k", "000");
                    } else if (salary.contains("万")) {
                        salary = salary.replaceAll("万", "0000");
                    } else if (salary.contains("元")) {
                        salary = salary.replaceAll("元", "");
                    } else if (salary.contains("w")) {
                        salary = salary.replaceAll("w", "0000");
                    }
                    String[] array = salary.split("~");
                    String min = array[0].trim();
                    String max = array[1].trim();
                    if (max.contains("不等") || max.contains("以上")) {
                        max = min;
                    }
                    recruit.setSalaryMin(Integer.parseInt(min));
                    recruit.setSalaryMax(Integer.parseInt(max));

                } else if ("面议".equals(salary)) {
                    recruit.setSalaryType("1");
                } else if(salary != null && salary.contains("面议")) {
                    recruit.setSalaryType("1");
                } else if(salary == null) {
                    recruit.setSalaryType("0");
                } else {
                    // 异常数据
                    recruit.setSalaryType("2");
                }

                recruit.setState(getState(checkstate));
                recruit.setContent(comment != null ? comment.replaceAll("/ueditor/jsp/upload", contentUrl + "/ueditor/jsp/upload") : "");
                recruit.setJobCategory(worktype);
                recruit.setJobName(jobname);
                recruit.setNumber(number);
                recruit.setArea(area);
                recruit.setMajors(majors);
                recruit.setEducation(education);
                recruit.setRecruitContact(linkman);
                recruit.setRecruitMobile(tel);
                recruit.setRecruitWebsite(recruiturl);
                recruit.setEmail(email);
                recruit.setType(getType(recruittype));
                recruit.setStateContent(checkstatecontent);
                recruit.setPositionIds(getPositionIds(positionList, position_ids));
                recruit.setPositionNames(position_names);
                if (companyid != null) {
                    Company company = getCompanyId(companyList, companyid);
                    if (company != null) {
                        recruit.setCompanyId(company.getId());
                        recruit.setCompanyName(company.getName());
                    } else {
                        recruit.setCompanyId(0);
                    }
                }
                recruit.setPushFlag("1".equals(push_flag) ? "0" : "1");
                recruit.setDeleted("0".equals(del_flag) ? 0 : 1);

                i ++;
                if (recruitService.save(recruit)) {
                    log.info("招聘信息：{} 数量：{} 个", title, i);
                    List<PositionMatching> list;
                    if (push_list == null) {
                        continue;
                    }
                    list = getPositionMatching(push_list, recruit.getId(), CheckRecordConstants.CHECK_RECRUIT, recruit.getPositionIds());
                    if (list == null) {
                        continue;
                    }
                    j ++;
                    positionMatchingService.saveBatch(list);
                    log.info("插入匹配信息：{} 数量：{} 个 旧信息： {}", title, j, push_list);
                }
            }

            long overTime = System.currentTimeMillis();
            long finishTime = (overTime - beginTime) / 1000;
            log.info("完成时间 : {} 分", finishTime);
            return JsonResult.ok(String.format("完成时间 : %s 分", finishTime));
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                rs.close();
                st.close();
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return JsonResult.ok();
    }


    /**
     * 查询所有单位信息
     * @return
     */
    private List<Company> getCompanyList() {
        return companyService.list();
    }

    /**
     * 查询原始
     * @return
     */
    private Company getCompanyId(List<Company> companyList, String oldId) {
        for(Company company : companyList) {
            if (oldId.equals(company.getOldId())) {
                return company;
            }
        }
        return null;
    }

    private String getState(Integer state) {
        switch (state) {
            case 0 : return "0";
            case 1 : return "1";
            case -1 : return "2";
            case -2 : return "3";
            default: return "";
        }
    }

    private String getType(Integer type) {
        switch (type) {
            case 4 : return "1";
            case 5 : return "2";
            case 6 : return "3";
            default: return "4";
        }
    }

    /**
     * 查询所有职位信息
     * @return
     */
    private List<Position> getPositionList() {
        return positionService.list();
    }

    /**
     * 查询职位信息
     * @return
     */
    private String getPositionIds(List<Position> positionList, String ids) {
        if (StrUtil.isBlank(ids)) {
            return "";
        }
        String[] arr = ids.split(",");
        StringBuilder sr = new StringBuilder();
        for (String id : arr) {
            for(Position position : positionList) {
                if (id.equals(position.getOldId())) {
                    sr.append(position.getId()).append(",");
                }
            }
        }
        return sr.deleteCharAt(sr.length() - 1).toString();
    }

    private List<PositionMatching> getPositionMatching(String json, Integer id, String type, String ids) {
        if (StrUtil.isBlank(json)) {
            return null;
        }
        log.info("json : {}", json);
        if (!JSONUtil.isJsonArray(json)) {
            log.info("json error : {}", json);
            return null;
        }
        JSONArray array = JSONUtil.parseArray(json);
        String[] arrIds = ids.split(",");
        List<PositionMatching> list = new ArrayList<>();
        int size = array.size();
        if (arrIds.length == size) {
            for (int i = 0; i < size; i ++) {
                PositionMatching p = new PositionMatching();
                p.setType(type);
                p.setPositionId(Integer.parseInt(arrIds[i]));
                p.setBusinessId(id);
                JSONObject j = array.getJSONObject(i);
                p.setPositionName(j.getStr("name"));
                p.setNumber(Integer.parseInt(j.getStr("type")));
                if (j.getStr("oneLabel") != null) {
                    p.setMatchingOne(j.getStr("oneLabel"));
                    p.setMatchingOneValue(Long.valueOf(j.getStr("one")));
                }
                if (j.getStr("twoLabel") != null) {
                    p.setMatchingTwo(j.getStr("twoLabel"));
                    p.setMatchingTwoValue(Long.valueOf(j.getStr("two")));
                }
                if (j.getStr("threeLabel") != null) {
                    p.setMatchingThree(j.getStr("threeLabel"));
                    p.setMatchingThreeValue(Long.valueOf(j.getStr("three")));
                }
                list.add(p);
            }
        }

        return list;
    }

}
